package com.rency.common.manager.services;

import java.text.ParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.rency.common.sequence.beans.Sequence;
import org.rency.common.sequence.service.SequenceRepository;
import org.rency.common.trigger.schedule.repository.DaemonTaskTriggerDO;
import org.rency.common.trigger.schedule.repository.DaemonTaskTriggerRepository;
import org.rency.common.trigger.service.ScheduleService;
import org.rency.common.utils.converts.JsonConvert;
import org.rency.common.utils.domain.RespBody;
import org.rency.common.utils.domain.SpringContextHolder;
import org.rency.common.utils.tool.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.rency.common.manager.ModelEnum;
import com.rency.common.manager.ServletUtils;

@Component
public class ServiceProcessor {

	public static ServiceProcessor getInstance(){
		return new ServiceProcessor();
	}
	
	public String service(String url){
		Map<String, String> parameters = getParameters(url);
		if(url.indexOf("?") != -1){
			url = url.substring(0, url.indexOf("?"));
		}
		
		if (url.equals("basic.json")) {
			Map<String, Object> data = getBasicData();
			return returnJSONResult(true,null,data);
		}
		
		/***************************** Sequence序列号 **********************************/
		if (url.equals(ModelEnum.SEQUENCE.getCode()+"/loadAll.json")) {
			SequenceRepository sequenceRepository = SpringContextHolder.getBean(SequenceRepository.class);
			List<Sequence> list = sequenceRepository.loadAll();
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("list", list);
			return returnJSONResult(true,null,data);
		}
		
		if (url.equals(ModelEnum.SEQUENCE.getCode()+"/find.json")) {
			SequenceRepository sequenceRepository = SpringContextHolder.getBean(SequenceRepository.class);
			Sequence sequence = sequenceRepository.find(parameters.get("seqName"));
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("sequence", sequence);
			return returnJSONResult(true,null,data);
		}
		
		if (url.equals(ModelEnum.SEQUENCE.getCode()+"/remove.json")) {
			SequenceRepository sequenceRepository = SpringContextHolder.getBean(SequenceRepository.class);
			boolean isSuccess = sequenceRepository.delete(parameters.get("seqName"));
			return returnJSONResult(isSuccess,isSuccess ? "删除成功" : "删除失败",null);
		}
		
		if (url.equals(ModelEnum.SEQUENCE.getCode()+"/add.json")) {
			SequenceRepository sequenceRepository = SpringContextHolder.getBean(SequenceRepository.class);
			Sequence sequence = null;
			try{
				sequence = build(parameters);
			}catch(IllegalArgumentException e){
				return returnJSONResult(false,e.getMessage(),null);
			}
			boolean isSuccess = sequenceRepository.save(sequence);
			return returnJSONResult(isSuccess,isSuccess ? "添加成功" : "添加失败",null);
		}
		
		/***************************** Trigger定时任务 **********************************/
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/loadAll.json")) {
			DaemonTaskTriggerRepository daemonTaskTriggerRepository = SpringContextHolder.getBean(DaemonTaskTriggerRepository.class);
			List<DaemonTaskTriggerDO> list = daemonTaskTriggerRepository.loadAll();
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("list", list);
			return returnJSONResult(true,null,data);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/find.json")) {
			DaemonTaskTriggerRepository daemonTaskTriggerRepository = SpringContextHolder.getBean(DaemonTaskTriggerRepository.class);
			DaemonTaskTriggerDO task = daemonTaskTriggerRepository.find(parameters.get("triggerName"));
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("task", task);
			return returnJSONResult(true,null,data);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/fireTrigger.json")) {
			ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
			boolean isSuccess = scheduleService.fireTrigger(parameters.get("triggerName"));
			return returnJSONResult(isSuccess,isSuccess ? "触发成功" : "触发失败",null);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/pauseTriggers.json")) {
			ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
			boolean isSuccess = scheduleService.pauseTriggers(parameters.get("triggerName"));
			return returnJSONResult(isSuccess,isSuccess ? "暂停成功" : "暂停失败",null);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/pauseAllTriggers.json")) {
			ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
			boolean isSuccess = scheduleService.pauseAllTriggers();
			return returnJSONResult(isSuccess,isSuccess ? "暂停成功" : "暂停失败",null);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/resumeAllTriggers.json")) {
			ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
			boolean isSuccess = scheduleService.resumeAllTriggers();
			return returnJSONResult(isSuccess,isSuccess ? "恢复成功" : "恢复失败",null);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/resumeTriggers.json")) {
			ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
			boolean isSuccess = scheduleService.resumeTriggers(parameters.get("triggerName"));
			return returnJSONResult(isSuccess,isSuccess ? "恢复成功" : "恢复失败",null);
		}
		
		if (url.equals(ModelEnum.TRIGGER.getCode()+"/modifyCronExpression.json")) {
			ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
			boolean isSuccess = scheduleService.modifyCronExpression(parameters.get("triggerName"),parameters.get("cronExpression"));
			return returnJSONResult(isSuccess,isSuccess ? "表达式修改成功" : "表达式修改失败",null);
		}		
		
		return returnJSONResult(false, "Do not support this request, please contact with administrator.",null);
	}
	
	public static Map<String, String> getParameters(String url) {
        if (url == null || (url = url.trim()).length() == 0) {
            return Collections.<String, String> emptyMap();
        }

        String parametersStr = ServletUtils.subString(url, "?", null);
        if (parametersStr == null || parametersStr.length() == 0) {
            return Collections.<String, String> emptyMap();
        }

        String[] parametersArray = parametersStr.split("&");
        Map<String, String> parameters = new LinkedHashMap<String, String>();

        for (String parameterStr : parametersArray) {
            int index = parameterStr.indexOf("=");
            if (index <= 0) {
                continue;
            }

            String name = parameterStr.substring(0, index);
            String value = parameterStr.substring(index + 1);
            parameters.put(name, value);
        }
        return parameters;
    }
	
	public static String returnJSONResult(boolean isSuccess,String returnMessage, Map<String, Object> data) {
        RespBody resp = new RespBody();
        resp.setSuccess(isSuccess);
        resp.setMessage(returnMessage);
        resp.setData(data);
        return JsonConvert.toJSONString(resp);
    }
	
	private Sequence build(Map<String, String> param){
		String name = param.get("name");
		String currentValue = param.get("currentValue");
		String increment = param.get("increment");
		String total = param.get("total");
		String threshold = param.get("threshold");
		Assert.notNull(name, "序列号名称不能为空");
		Assert.notNull(currentValue, "序列号起始值不能为空");
		Assert.notNull(increment, "序列号步值不能为空");
		Assert.notNull(total, "序列号单次取值数量不能为空");
		Assert.notNull(threshold, "序列号刷新阀值不能为空");
		Sequence sequence = new Sequence();
		sequence.setName(name);
		sequence.setCurrentValue(Long.getLong(currentValue));
		sequence.setIncrement(Integer.getInteger(increment));
		sequence.setTotal(Integer.getInteger(total));
		sequence.setThreshold(Integer.getInteger(threshold));
		return sequence;
	}

	private Map<String, Object> getBasicData(){
		Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
        dataMap.put("Version", ServletUtils.VERSION);
        dataMap.put("JavaVMName", System.getProperty("java.vm.name"));
        dataMap.put("JavaVersion", System.getProperty("java.version"));
        dataMap.put("JavaClassPath", System.getProperty("java.class.path"));
        try {
			dataMap.put("StartTime", DateUtils.parseDate(ServletUtils.getStartTime(),DateUtils.PATTERN_FULLDATETIME_MILLS));
		} catch (ParseException e) {
			dataMap.put("StartTime", ServletUtils.getStartTime());
		}
        return dataMap;
	}
}
